package net.bwie.realtime.dws.log.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Weather {
    public static JSONObject getWeatherInfo(String adcode, String key) throws Exception {
        String url = "https://restapi.amap.com/v3/weather/weatherInfo";
        String requestUrl = url + "?key=" + key + "&city=" + adcode;

        URL obj = new URL(requestUrl);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        JSONObject result = JSONObject.parseObject(response.toString());
        return result;
    }

    public static void main(String[] args) {
        try {
            String adcode = "城市编码"; // 例如：110000（北京市）
            String key = "你的开发者Key";

            JSONObject weatherInfo = getWeatherInfo(adcode, key);
            JSONArray forecasts = weatherInfo.getJSONArray("forecasts");
            JSONObject todayForecast = forecasts.getJSONObject(0);
            JSONArray casts = todayForecast.getJSONArray("casts");

            for (int i = 0; i < casts.size(); i++) {
                JSONObject cast = casts.getJSONObject(i);
                String date = cast.getString("date");
                String week = cast.getString("week");
                String dayWeather = cast.getString("dayweather");
                String nightWeather = cast.getString("nightweather");

                System.out.println(date + " " + week + " " + dayWeather + "转" + nightWeather);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
